package com.mazaiting.screen.video

import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.os.IBinder
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mazaiting.log.L
import com.mazaiting.permission.PermissionResult
import com.mazaiting.permission.Permissions
import com.mazaiting.permission.util.PermissionUtil
import com.mazaiting.permission.util.State
import kotlinx.android.synthetic.main.activity_video.*
import android.media.projection.MediaProjection
import com.mazaiting.screen.R


/**
 * 录屏界面
 */
@Permissions(
    value = [Manifest.permission.RECORD_AUDIO],
    code = VideoActivity.RECORD_REQUEST_CODE
)
class VideoActivity : AppCompatActivity() {

    companion object {
        /**
         * 视频录屏页面
         * @param context 上下文
         */
        fun newInstance(context: Context) {
            val intent = Intent(context, VideoActivity::class.java)
            // 新的任务栈
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }

        /**
         * 录屏请求码
         */
        private const val VIDEO_REQUEST_CODE = 0x100
        /**
         * 录音请求码
         */
        const val RECORD_REQUEST_CODE = 0x101
    }

    /**
     * 媒体工程
     */
    private var mProjectionManager: MediaProjectionManager? = null
    /**
     * 视频服务
     */
    private var mVideoService: VideoService? = null

    /**
     * 服务连接
     */
    private val mConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            val binder = service as VideoService.VideoBinder
            // 获取服务
            mVideoService = binder.service
        }

        override fun onServiceDisconnected(className: ComponentName) {}
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video)
        // 获取媒体工程管理者
        mProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager

        initView()

        PermissionUtil.requestPermission(this)
    }

    /**
     * 初始化 View
     */
    private fun initView() {
        // 开始录屏
        video_btn_start.setOnClickListener {
            // 绑定服务
            val intent = Intent(this, VideoService::class.java)
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
            // 开始录屏
            val captureIntent = mProjectionManager?.createScreenCaptureIntent()
            startActivityForResult(captureIntent, VIDEO_REQUEST_CODE)
        }
        // 结束录屏
        video_btn_stop.setOnClickListener {
            if (mVideoService?.isRunning!!) {
                mVideoService?.stopRecord(object : VideoService.IVideoListener {
                    override fun onVideo(path: String) {
                        L.d("视频路径: $path")
                        Toast.makeText(this@VideoActivity, "录屏成功", Toast.LENGTH_SHORT).show()
                    }
                })
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == VIDEO_REQUEST_CODE) {
            // 判断啊请求码和数据
            if (data != null && resultCode != 0) {
                dealData(resultCode, data)
                quitApplication()
            } else {
                Toast.makeText(this@VideoActivity, "请允许截取您的屏幕上所有的内容!", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionUtil.onRequestPermissionsResult(this, requestCode, permissions, grantResults)
    }

    /**
     * 权限处理
     *
     * @param state       权限状态
     * @param permissions 权限列表: 注意可为空
     */
    @PermissionResult(RECORD_REQUEST_CODE)
    fun permissionResult(state: State, permissions: List<String>?) {
        when (state) {
            State.NOT_SHOW -> {
                // 勾选不再显示
                Toast.makeText(this@VideoActivity, "权限勾选不再显示", Toast.LENGTH_SHORT).show()
            }
            State.SUCCESS
            -> {
                // 请求成功
                Toast.makeText(this@VideoActivity, "权限请求成功", Toast.LENGTH_SHORT).show()
            }
            State.DENIED -> {
                // 拒绝
                Toast.makeText(this@VideoActivity, "权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 处理数据
     * @param resultCode 结果码
     * @param data 视图数据
     */
    private fun dealData(resultCode: Int, data: Intent) {
        // 获取媒体工程
        val mediaProjection = mProjectionManager?.getMediaProjection(resultCode, data)
        // 设置媒体工程
        mVideoService?.setMediaProject(mediaProjection!!)
        // 开启录制
        mVideoService?.startRecord()
    }

    /**
     * 退出应用, 点击返回键不退出应用
     */
    private fun quitApplication() {
        val home = Intent(Intent.ACTION_MAIN)
        home.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        home.addCategory(Intent.CATEGORY_HOME)
        startActivity(home)
    }

    override fun onDestroy() {
        // 解绑服务
        unbindService(mConnection)
        super.onDestroy()
        mVideoService = null
        mProjectionManager = null
    }

}
